package com.example.hszpad.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.hszpad.MyApplication;
import com.example.hszpad.R;
import com.example.hszpad.adapter.BaseRecyclerAdapter;
import com.example.hszpad.adapter.SmartViewHolder;
import com.example.hszpad.bean.ConfigBean;
import com.example.hszpad.bean.DataPointBean;
import com.example.hszpad.bean.MenuItemBean;
import com.example.hszpad.modbus.ModbusSocketElectricClient;
import com.example.hszpad.util.FileUtil;
import com.example.hszpad.util.XmlParserUtil;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;
import com.intelligt.modbus.jlibmodbus.utils.DataUtils;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class HSZViewFragmentElectric extends Fragment implements ModbusSocketElectricClient.OnReceiveListener {


    private ImageView iv_electric;
    private RecyclerView recyclerView;
    private BaseRecyclerAdapter<MenuItemBean> recyclerChildAdapter;
    private List<MenuItemBean> menuItemBeanChildList;
    private MenuItemBean curChildBean;
    private AbsoluteLayout fl_content;
    private int changeState = 1; //1常规参数 2智能化参数

    private ConfigBean configBean;
    private ModbusSocketElectricClient modbusSocketClient;
    private Map<String, DataPointBean> dataPointBeanMap;
    private List<DataPointBean> showPointList;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_hszview_fragment_electric, container, false);
        iv_electric = view.findViewById(R.id.iv_electric);
        fl_content = view.findViewById(R.id.fl_content);
        recyclerView = view.findViewById(R.id.recyclerView);
        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(
                1632,
                1062,
                0,
                0);
        iv_electric.setLayoutParams(layoutParams);
        view.findViewById(R.id.btn_change).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curChildBean != null) {
                    if (curChildBean.getId() == 1) {
                        if (changeState == 1) {
                            Glide.with(getActivity()).load(R.drawable.ic_content_electric2).into(iv_electric);
                            changeState = 2;
                        } else {
                            Glide.with(getActivity()).load(R.drawable.ic_content_electric1).into(iv_electric);
                            changeState = 1;
                        }
                    }
                }
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        menuItemBeanChildList = new ArrayList<>();
        MenuItemBean bean = new MenuItemBean(1, "电站", 1, R.drawable.ic_home_white_24dp, true);
        menuItemBeanChildList.add(bean);
        bean = new MenuItemBean(2, "配电", 1, R.drawable.ic_home_white_24dp, false);
        menuItemBeanChildList.add(bean);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerChildAdapter = new BaseRecyclerAdapter<MenuItemBean>(menuItemBeanChildList, R.layout.layout_view_menu_item, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MenuItemBean itemBean = menuItemBeanChildList.get(position);
                if (itemBean.isSelect()) {
                    return;
                } else {
                    for (int i = 0; i < menuItemBeanChildList.size(); i++) {
                        menuItemBeanChildList.get(i).setSelect(false);
                    }
                    itemBean.setSelect(true);
                    if (itemBean != curChildBean) {
                        changeState = 1;
                        if (itemBean.getId() == 1) {
                            Glide.with(getActivity()).load(R.drawable.ic_content_electric1).into(iv_electric);
                            showPoint(false);
                        } else {
                            Glide.with(getActivity()).load(R.drawable.ic_content_electric3).into(iv_electric);
                            showPoint(true);
                        }
                        curChildBean = itemBean;
                    }
                }
                recyclerChildAdapter.notifyDataSetChanged();
                recyclerChildAdapter.notifyListDataSetChanged();
            }
        }) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, MenuItemBean model, int position) {
                holder.text(R.id.tv_title, model.getName());
                if (model.isSelect()) {
                    holder.viewBgImageId(R.id.ll_content, R.drawable.ic_bg_menu_pressed);
                    holder.textColorId(R.id.tv_title, R.color.colorSecondMenuNormal);
                } else {
                    holder.viewBgImageId(R.id.ll_content, R.drawable.ic_bg_menu_normal);
                    holder.textColorId(R.id.tv_title, R.color.colorSecondMenuPressed);
                }
            }
        };
        recyclerView.setAdapter(recyclerChildAdapter);
        curChildBean = menuItemBeanChildList.get(0);
        changeState = 1;
        Glide.with(getActivity()).load(R.drawable.ic_content_electric1).into(iv_electric);
        configBean = MyApplication.configBean;
        if (configBean == null) {
            Toast.makeText(getContext(), "未找到配置文件!", Toast.LENGTH_SHORT).show();
            return view;
        }
        modbusSocketClient = new ModbusSocketElectricClient(getActivity());
        new Thread() {
            @Override
            public void run() {
                dataPointBeanMap = configBean.getDataPointBeanMap();
                showPointList = configBean.getDataPointBeanOnShowList();
                if (null != dataPointBeanMap) {
                    if (configBean == null) {
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (String i : dataPointBeanMap.keySet()) {
                                DataPointBean bean = dataPointBeanMap.get(i);
                                if (null != bean) {
                                    if (bean.getType() == 1) {
                                        TextView tv = new TextView(getContext());
                                        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(
                                                bean.getWidth(),
                                                bean.getHeight(),
                                                bean.getX(),
                                                bean.getY());
                                        tv.setLayoutParams(layoutParams);
                                        tv.setVisibility(View.GONE);
//                                        tv.setBackgroundColor(Color.RED);
                                        tv.setGravity(Gravity.CENTER);
                                        tv.setTextSize(8);
                                        if (bean.getIsLight() == 1) {
                                            tv.setTextColor(HSZViewFragmentElectric.this.getContext().getResources().getColor(R.color.colorAccent));
                                        } else {
                                            tv.setTextColor(HSZViewFragmentElectric.this.getContext().getResources().getColor(R.color.colorPrimary));
                                        }
                                        fl_content.addView(tv);
                                        tv.setText("0.00");
                                        bean.setTextView(tv);
                                    } else {
                                        ImageView iv = new ImageView(getContext());
                                        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(
                                                bean.getWidth(),
                                                bean.getHeight(),
                                                bean.getX(),
                                                bean.getY());
                                        iv.setLayoutParams(layoutParams);
                                        iv.setVisibility(View.GONE);
                                        fl_content.addView(iv);
                                        bean.setImageView(iv);
                                        Glide.with(getContext()).load(new File(FileUtil.getConfigPath() + bean.getOffImage())).into(iv);
                                    }
                                }
                            }
                            for (DataPointBean bean : showPointList) {
                                if (null != bean) {
                                    if (bean.getType() == 1) {
                                        TextView tv = new TextView(getContext());
                                        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(
                                                bean.getWidth(),
                                                bean.getHeight(),
                                                bean.getX(),
                                                bean.getY());
                                        tv.setLayoutParams(layoutParams);
                                        tv.setVisibility(View.GONE);
//                                        tv.setBackgroundColor(Color.RED);
                                        tv.setGravity(Gravity.CENTER);
                                        tv.setTextSize(8);
                                        if (bean.getIsLight() == 1) {
                                            tv.setTextColor(HSZViewFragmentElectric.this.getContext().getResources().getColor(R.color.colorAccent));
                                        } else {
                                            tv.setTextColor(HSZViewFragmentElectric.this.getContext().getResources().getColor(R.color.colorPrimary));
                                        }
                                        tv.setText("0.00");
                                        fl_content.addView(tv);
                                        bean.setTextView(tv);
                                    } else {
                                        ImageView iv = new ImageView(getContext());
                                        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(
                                                bean.getWidth(),
                                                bean.getHeight(),
                                                bean.getX(),
                                                bean.getY());
                                        iv.setLayoutParams(layoutParams);
                                        iv.setVisibility(View.GONE);
//                                        iv.setBackgroundColor(Color.RED);
                                        fl_content.addView(iv);
                                        bean.setImageView(iv);
                                        Glide.with(getContext()).load(new File(FileUtil.getConfigPath() + bean.getOnImage())).into(iv);
                                    }
                                }
                            }
                        }
                    });
                }
                TcpParameters tcpParameters = new TcpParameters();
                try {
                    tcpParameters.setHost(InetAddress.getByName(configBean.getIp()));
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                tcpParameters.setKeepAlive(true);
                tcpParameters.setPort(configBean.getPort());
                modbusSocketClient.setTcpParameters(tcpParameters);
                modbusSocketClient.setOnReceiveListener(HSZViewFragmentElectric.this);
                modbusSocketClient.conn();
            }
        }.start();
        return view;
    }

    @Override
    public void onDestroyView() {
        if (modbusSocketClient != null) {
            modbusSocketClient.setOnReceiveListener(null);
            modbusSocketClient.close();
        }
        super.onDestroyView();
    }

    @Override
    public void receive(int startAddress, int quality, byte[] registers) {
        if (dataPointBeanMap != null && !dataPointBeanMap.isEmpty()) {
            for (String i : dataPointBeanMap.keySet()) {
                DataPointBean bean = dataPointBeanMap.get(i);
                if (null != bean && bean.getOffset() == startAddress) {
                    //获取数值
                    switch (bean.getDataType()) {
                        case "INT":
                            int val = DataUtils.BeToInt(registers, bean.getAddress() * 2);
                            float res = 0.0f;
                            if ("除100".equals(bean.getCondition())) {
                                res = val / 100.0f;
                            } else if ("除10".equals(bean.getCondition())) {
                                res = val / 10.0f;
                            } else if ("除1000".equals(bean.getCondition())) {
                                res = val / 1000.0f;
                            } else {
                                res = val * 1.0f;
                            }
                            bean.setVal(String.format("%.02f", res));
                            break;
                        case "FLOAT":
                            float val2 = DataUtils.BeToFloat(registers, bean.getAddress() * 2);
                            if ("除100".equals(bean.getCondition())) {
                                val2 = val2 / 100.0f;
                            } else if ("除10".equals(bean.getCondition())) {
                                val2 = val2 / 10.0f;
                            } else if ("除1000".equals(bean.getCondition())) {
                                val2 = val2 / 1000.0f;
                            } else {
                                val2 = val2 * 1.0f;
                            }
                            bean.setVal(String.format("%.02f", val2));
                            break;
                        case "BIT":
                            byte[] val3 = DataUtils.getByteArray(registers, bean.getAddress() * 2);
                            bean.setSwitchVal(val3[bean.getBitIndex()] > 0);
                            break;
                    }
                    if (bean.getType() == 1) {
                        bean.getTextView().setText(bean.getVal());
                    } else {
                        if (bean.isSwitchVal()) {
                            Glide.with(getContext()).load(new File(FileUtil.getConfigPath() + bean.getOnImage())).into(bean.getImageView());
                        } else {
                            Glide.with(getContext()).load(new File(FileUtil.getConfigPath() + bean.getOffImage())).into(bean.getImageView());
                        }
                    }
                }
            }
        }
    }

    @Override
    public void catchException(Exception e) {

    }

    private void showPoint(boolean visible) {
        if (dataPointBeanMap != null && !dataPointBeanMap.isEmpty()) {
            for (String i : dataPointBeanMap.keySet()) {
                DataPointBean bean = dataPointBeanMap.get(i);
                if (visible) {
                    if (bean.getType() == 1) {
                        bean.getTextView().setVisibility(View.VISIBLE);
                    } else {
                        bean.getImageView().setVisibility(View.VISIBLE);
                    }
                } else {
                    if (bean.getType() == 1) {
                        bean.getTextView().setVisibility(View.GONE);
                    } else {
                        bean.getImageView().setVisibility(View.GONE);
                    }
                }
            }
        }
        if (showPointList != null && !showPointList.isEmpty()) {
            for (DataPointBean bean : showPointList) {
                if (visible) {
                    if (bean.getType() == 1) {
                        bean.getTextView().setVisibility(View.VISIBLE);
                    } else {
                        bean.getImageView().setVisibility(View.VISIBLE);
                    }
                } else {
                    if (bean.getType() == 1) {
                        bean.getTextView().setVisibility(View.GONE);
                    } else {
                        bean.getImageView().setVisibility(View.GONE);
                    }
                }
            }
        }
    }
}
